<template>
    <section>
        <!--工具条-->
        <div class="section-content clearfix">
            <div class="grid-content bg-purple" v-if="usertype==2" :style="{backgroundColor:titleColor}">
                <div class="dev-title">集团流量使用情况</div>
                <div class="dev-title">总流量：{{flowInfo[0].value}}MB</div>

                <div class="dev-title">已使用流量：{{flowInfo[1].value}}MB</div>
                <div class="dev-title">剩余总流量：{{flowInfo[2].value}}MB</div>

            </div>
            <el-col :span="24" style="padding-bottom: 0px;margin-top: 10px;">
                <el-form @submit.native.prevent :inline="true" :model="filters">
                    <el-form-item>
                        <el-input v-model="filters.name" placeholder="设备名字" @keyup.enter.native="getUsers()"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-input v-model="filters.deviceSn" placeholder="SN" @keyup.enter.native="getUsers()">
                        </el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-select v-model="filters.overFlow" filterable placeholder="是否超出" @change="getUsers()">
                            <el-option key=" " label="全选" value=" ">
                            </el-option>
                            <el-option key="1" label="是" value="1">
                            </el-option>
                            <el-option key="0" label="否" value="0">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-select v-if="usertype==2" v-model="scade1" filterable placeholder="请选择组织"
                            @change="getUsers()">
                            <el-option key=" " label="全选" value=" ">
                            </el-option>
                            <el-option v-for="item in firmlist" :key="item.companyId" :label="item.name"
                                :value="item.companyId">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-select v-model="scade" filterable placeholder="请选择子用户" size="" @change="deviceList()">
                            <el-option :key="scade1" label="当前账户" :value="scade1">
                            </el-option>
                            <el-option v-for="item in userclist" :key="item.userId" :label="item.userName"
                                :value="item.userId">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button :type="buttonColor" v-on:click="getUsers">查询</el-button>
                    </el-form-item>
                    <el-form-item>
                        <el-button :type="buttonColor" v-on:click="reset_flow()">发起同步移动数据</el-button>
                    </el-form-item>
                    <el-form-item>
                        <el-button :type="buttonColor" v-on:click="excelGet()">导出数据</el-button>
                    </el-form-item>

                </el-form>
            </el-col>

            <!--列表-->
            <el-table :data="query" class="alarmshistory" :header-row-style="{backgroundColor: titleColor}" highlight-current-row v-loading="listLoading" @selection-change="selsChange"
                style="width: 100%;">


                <el-table-column type="index" label="序号" width="80" :index="indexMethod">
                </el-table-column>
                <el-table-column align="center" prop="name" label="设备名字" width="150">
                </el-table-column>
                <el-table-column align="center" prop="deviceSn" label="网关SN" width="200">
                </el-table-column>
                <el-table-column align="center" prop="iccid" label="iccid" width="200">
                </el-table-column>
                <el-table-column align="center" prop="pkgName" label="接入点名称" v-if="usertype==2">
                </el-table-column>

                <el-table-column align="center" prop="totalFlow" label="总流量">
                    <template scope="scope">

                        <span v-if="scope.row.totalFlow">
                            {{scope.row.totalFlow}} MB
                        </span>

                    </template>
                </el-table-column>

                <el-table-column align="center" prop="usedFlow" label="已使用流量">
                    <template scope="scope">

                        <span v-if="scope.row.usedFlow">
                            {{scope.row.usedFlow}} MB
                        </span>

                    </template>
                </el-table-column>

                <el-table-column align="center" prop="restFlow" label="剩余流量">
                    <template scope="scope">

                        <span v-if="scope.row.restFlow">
                            {{scope.row.restFlow}} MB
                        </span>

                    </template>
                </el-table-column>
                <el-table-column align="center" label="流量阈值">
                    <template scope="scope">

                        <span v-if="scope.row.alarmFlow">
                            {{scope.row.alarmFlow}}%
                        </span>

                    </template>
                </el-table-column>
                <el-table-column align="center" prop="overFlow" label="是否超出流量" :formatter="formatstate">
                </el-table-column>
                <el-table-column align="center" prop="activateTime" label="激活时间" width="200">
                </el-table-column>
                <!-- <el-table-column prop="flowTime" label="套餐失效时间">
                </el-table-column> -->
                <el-table-column align="center" prop="updateTime" label="更新时间" width="200">
                </el-table-column>
                <el-table-column align="center" label="操作">
                    <template scope="scope">

                        <span>

                            <el-button v-if="menubt.indexOf('/device_flow/put')>-1" @click="handleEdit( scope.row,1)"
                                type="small" plain>编辑</el-button>
                            <!-- <i title="设备升级" @click="handleEdit(scope.row)" type="warning" class="pb-icon icon-general_order"></i> -->
                        </span>

                    </template>

                </el-table-column>
            </el-table>

            <!--工具条-->
            <el-col :span="24" class="toolbar">
                <!-- <el-button type="danger" @click="batchRemove(1)" :disabled="this.sels.length===0">批量升级</el-button>
                <el-button type="danger" @click="batchRemove(2)" :disabled="this.sels.length===0">批量设备升级</el-button> -->
                <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="10"
                    :total="total" style="float:right;">
                </el-pagination>
            </el-col>
        </div>
        <!--编辑界面-->
        <el-dialog title="编辑" v-show="editFormVisible" v-model="editFormVisible" :custom-class="dialogTitleColor" @close="editFormVisible=false">
            <div slot="footer" style="text-align: left; ">
                <el-form @submit.native.prevent :model="editForm" label-width="120px" :rules="editFormRules"
                    ref="editForm">
                    <el-form-item label="流量阈值">
                        <el-input v-model="editForm.alarmFlow" type="number" :max="100" :min="0" placeholder="请输入">

                        </el-input>
                    </el-form-item>


                </el-form>
                <div slot="footer" class="dialog-footer" style="text-align:center;">
                    <el-button @click.native="editFormVisible = false">取消</el-button>
                    <el-button :type="buttonColor" @click.native="editSubmit" :loading="editLoading">提交</el-button>
                </div>
                </el-form>

            </div>
        </el-dialog>
        <!-- <el-dialog title="命令" v-show="upgradeVisible" v-model="editFormVisible" @close="upgradeVisible=false">
            <div slot="footer" style="text-align: left; ">
                <el-form @submit.native.prevent :model="editForm" label-width="120px" :rules="editFormRules" ref="editForm">
                    <el-form-item label="设备固件包">
                        <el-select v-model="editForm.deviceUpgradeId" placeholder="请选择">
                            <el-option v-for="(item,index) in bag" :key="item.id" :label="item.name" :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="设备固件参数表">
                        <el-select v-model="editForm.deviceArgumentId" placeholder="请选择">
                            <el-option v-for="(item,index) in parameter" :key="item.id" :label="item.name" :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="ftp账号">
                        <el-input v-model="editForm.ftpUser" type="input"></el-input>
                    </el-form-item>

                    <el-form-item label="ftp密码">
                        <el-input type="input" v-model="editForm.ftpPassword "></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer" style="text-align:right;">
                    <el-button @click.native="upgradeVisible = false">取消</el-button>
                    <el-button :type="buttonColor" @click.native="upgrade" :loading="editLoading">提交</el-button>
                </div>
                </el-form>

            </div>
        </el-dialog> -->

        <el-dialog title="新增" v-show="addFormVisible" v-model="addFormVisible" :custom-class="dialogTitleColor" @close="addFormVisible=false">
            <div slot="footer" style="text-align: left; ">
                <el-form @submit.native.prevent :model="addForm" label-width="100px" :rules="addFormRules"
                    ref="addForm">
                    <el-form-item label="名字" prop="name">
                        <el-input v-model="addForm.name" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="备注" prop="remark">
                        <el-input type="textarea" v-model="addForm.remark"></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer" style="text-align: right;">
                    <el-button @click.native="addFormVisible = false">取消</el-button>
                    <el-button :type="buttonColor" @click.native="addSubmit" :loading="addLoading">提交</el-button>
                </div>
            </div>
        </el-dialog>
    </section>
</template>

<script>
    // import util from './../common/js/util'
    //import NProgress from 'nprogress'
    import {
        user_query,
        device_query,
        device_flow_query,
        device_flow_put,
        device_flow_get,
        device_flow_reset_flow,
        dict_query,
        user_querycompany
    } from '../../../api/api';

    export default {
        data() {
            return {
                userclist:[],
                userID: '',
                firmlist: '',
                scade1: '',
                scade: '',
                devicelist: [],
                usertype: '',
                flowInfo: '',
                upgradeVisible: false,
                bagid: '',
                parameterid: '',
                bag: '',
                parameter: '',
                filters: {
                    name: '',
                    deviceSn: '',
                    overFlow: ''
                },
                query: [],
                total: 0,
                page: 1,
                listLoading: false,
                sels: [], //列表选中列

                editFormVisible: false, //编辑界面是否显示
                editLoading: false,
                editFormRules: {
                    name: [{
                        required: true,
                        message: '请输入姓名',
                        trigger: 'blur'
                    }, {
                        min: 1,
                        max: 20,
                        message: '长度在 1 到 20 个字符',
                        trigger: 'blur'
                    }]
                },
                //编辑界面数据
                editForm: {
                    id: '',
                    alarmFlow: '',

                },

                addFormVisible: false, //新增界面是否显示
                addLoading: false,
                addFormRules: {
                    name: [{
                        required: true,
                        message: '请输入姓名',
                        trigger: 'blur'
                    }, {
                        min: 1,
                        max: 20,
                        message: '长度在 1 到 20 个字符',
                        trigger: 'blur'
                    }],
                    path: [{
                            required: true,
                            message: '请输入path',
                            trigger: 'blur'
                        }

                    ]
                },
                //新增界面数据
                addForm: {
                    name: '',
                    remark: ''
                }

            }
        },
        computed:{
            buttonColor(){
                return this.$store.state.buttonColor
            },
            titleColor(){
                return this.$store.state.titleColor
            },
            dialogTitleColor(){
                return this.$store.state.dialogTitleColor
            },
        },
        methods: {
            base64(s) {
                return window.btoa(unescape(encodeURIComponent(s)))
            },
            excelGet(){
                let para = {
                    pageNo: 1,
                    pageSize: 10000,
                    name: this.filters.name,
                    companyId: this.scade1,
                    deviceUserId: this.scade,
                    deviceSn: this.filters.deviceSn,
                    overFlow: this.filters.overFlow
                };
                //NProgress.start();
                device_flow_query(para).then((res) => {
                    this.begCode(res.code, res.message);
                    let num=[];
                    for(let i in res.data.list){
                        if(res.data.list[i].overFlow==0){
                            res.data.list[i].overFlow='否'
                        }else if(res.data.list[i].overFlow==1){

                            res.data.list[i].overFlow='是'
                        }
                        num.push({
                            name:' '+res.data.list[i].name,
                            deviceSn:'SN:'+res.data.list[i].deviceSn,
                            iccid:' '+res.data.list[i].iccid,
                            pkgName:res.data.list[i].pkgName,
                            totalFlow:res.data.list[i].totalFlow,
                            usedFlow:res.data.list[i].usedFlow,
                            restFlow:res.data.list[i].restFlow,
                            alarmFlow:res.data.list[i].alarmFlow+'%',
                            overFlow:res.data.list[i].overFlow,
                            activateTime:res.data.list[i].activateTime+' ',
                            updateTime:res.data.list[i].updateTime+' ',
                        })
                    }
                    this.tableToExcel(num);
                    //NProgress.done();
                });
            },
            tableToExcel(jsonData) {
                //要导出的json数据
                // const jsonData = [{
                //         name: '路人甲',
                //         phone: '123456',
                //         email: '123@123456.com'
                //     },
                //     {
                //         name: '炮灰乙',
                //         phone: '123456',
                //         email: '123@123456.com'
                //     },
                //     {
                //         name: '土匪丙',
                //         phone: '123456',
                //         email: '123@123456.com'
                //     },
                //     {
                //         name: '流氓丁',
                //         phone: '123456',
                //         email: '123@123456.com'
                //     },
                // ]
                //列标题
                // let str = '<tr><td>设备名</td><td>设备SN</td><td>接入点名称</td><td>总流量</td><td>已使用流量</td><td>剩余流量</td><td>流量阈值</td><td>是否超出流量</td><td>激活时间</td><td>更新时间</td></tr>';
                let str = '设备名,网关SN,iccid,接入点名称,总流量,已使用流量,剩余流量,流量阈值,是否超出流量,激活时间,更新时间\n';
                for(let i = 0 ; i < jsonData.length ; i++ ){
        for(let item in jsonData[i]){
            str+=`${jsonData[i][item] + '\t'},`;     
        }
        str+='\n';
      }
      //encodeURIComponent解决中文乱码
      let uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(str);
      //通过创建a标签实现
      let link = document.createElement("a");
      link.href = uri;
      //对下载的文件命名
      link.download =  "网关流量表.xls";
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);

                
                //循环遍历，每行加入tr标签，每个单元格加td标签
    //             for (let i = 0; i < jsonData.length; i++) {
    //                 str += '<tr>';
    //                 for (let item in jsonData[i]) {
    //                     //增加\t为了不让表格显示科学计数法或者其他格式
    //                     str += `<td>${ jsonData[i][item] + '\t'}</td>`;
    //                 }
    //                 str += '</tr>';
    //             }
    //             //Worksheet名
    //             let worksheet = 'Sheet1'
    //             let uri = 'data:application/vnd.ms-excel;base64,';

    //             //下载的表格模板数据
    //             let template = `<html xmlns:o="urn:schemas-microsoft-com:office:office" 
    //   xmlns:x="urn:schemas-microsoft-com:office:excel" 
    //   xmlns="http://www.w3.org/TR/REC-html40">
    //   <head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>
    //     <x:Name>${worksheet}</x:Name>
    //     <x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>
    //     </x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->
    //     </head><body><table>${str}</table></body></html>`;
    //             //下载模板
    //             window.location.href = uri + this.base64(template)
            },
            select_scade1(s) {
                let para = {
                    pageNo: 1,
                    pageSize: 9999,
                    type: 0,
                    companyId: this.scade1,
                    authType: 0
                    
                }

                user_query(para).then((res) => {

                    this.begCode(res.code, res.message);
                    this.userclist = res.data.list;
                    console.log(this.scade1)
                    if (this.scade1) {
                        this.userID = this.scade1;
                        this.scade = "";
                    } else {
                        this.userID = 0;
                        console.log(this.userID)
                    }
                    console.log()


                });

                this.deviceList();
                // this.getUsers()
            },
            deviceList() {
                let para = {
                    pageNo: 1,
                    pageSize: 9999,
                    deviceUserId: this.scade

                };
                device_query(para).then((res) => {
                    this.begCode(res.code, res.message);
                    this.devicelist = res.data.list;
                    if (this.devicelist.length > 0) {
                        // this.filters.name = this.devicelist[0].name;
                    } else {
                        this.filters.name = '';
                    }

                    this.getUsers();
                    //NProgress.done();
                });
            },
            indexMethod(index) {
                console.log(this.page)
                let num = (this.page - 1) * 10 + index + 1;
                return num;
            },
            reset_flow() {

                device_flow_reset_flow().then((res) => {
                    this.begCode(res.code, res.message);

                    if (res.code == 0) {
                        this.editLoading = false;
                        //NProgress.done();
                        this.$message({
                            message: '提交成功',
                            type: 'success'
                        });

                        this.getUsers();
                    }
                });
            },
            upgrade() {
                this.$confirm('确认升级吗？', '提示', {}).then(() => {
                    this.editLoading = true;
                    //NProgress.start();
                    let para = Object.assign({}, this.editForm);

                    device_upgrade_upgrade_by_condition(para).then((res) => {
                        this.begCode(res.code, res.message);

                        if (res.code == 0) {
                            this.editLoading = false;
                            //NProgress.done();
                            this.$message({
                                message: '提交成功',
                                type: 'success'
                            });
                            this.$refs['editForm'].resetFields();
                            this.upgradeVisible = false;
                            this.getUsers();
                        }
                    });
                });
            },
            upgradeEdit: function (type) {

                this.getlist(type);
                this.upgradeVisible = true;
                this.editForm = {
                    type: type,
                    ftpUser: '',
                    deviceUpgradeId: '',
                    deviceArgumentId: '',
                    ftpPassword: ''
                }
            },
            formatstate(row, column) {

                return row.overFlow == 1 ? '超出' : row.overFlow == 0 ? '否' : '未知';
            },
            special(index, row) {
                sessionStorage.setItem('facility_details', row.deviceId)
                this.$router.push({
                    path: '/devices/gatewaydis'
                })
            },

            formatSex: function (row, column) {
                return row.sex == 1 ? '男' : row.sex == 0 ? '女' : '未知';
            },
            handleCurrentChange(val) {
                this.page = val;
                this.getUsers();
            },
            //获取菜单列表
            getUsers() {
                if (this.menubt.indexOf('/device_flow/query') == -1) {
                    this.$message({
                        message: '您没有查询设备流量的权限',
                        type: 'warning'
                    });
                    return false;
                }
                let para = {
                    pageNo: this.page,
                    pageSize: 10,
                    name: this.filters.name,
                    companyId: this.scade1,
                    deviceUserId: this.scade,
                    deviceSn: this.filters.deviceSn,
                    overFlow: this.filters.overFlow,
                    // companyId: this.scade1
                };
                this.listLoading = true;
                //NProgress.start();
                device_flow_query(para).then((res) => {
                    this.begCode(res.code, res.message);
                    this.total = res.data.totalCount;
                    this.query = res.data.list;
                    this.page = res.data.pageNo;
                    this.listLoading = false;
                    //NProgress.done();
                });
                let para1 = {
                    pageNo: 1,
                    pageSize: 100,
                    name: 'TotalFlowInfo'
                }

                dict_query(para1).then((res) => {
                    this.begCode(res.code, res.message);
                    this.flowInfo = res.data.list;
                    //NProgress.done();
                });
            },
            //删除
            handleDel: function (index, row) {
                this.$confirm('确认删除该选项吗?', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    //NProgress.start();
                    let para = {
                        idList: [row.id]
                    };
                    device_model_delete(para).then((res) => {
                        this.begCode(res.code, res.message);
                        if (res.code == 0) {

                            this.listLoading = false;
                            //NProgress.done();
                            this.$message({
                                message: '删除成功',
                                type: 'success'
                            });
                            this.getUsers();

                        }
                    });
                }).catch(() => {

                });
            },
            //显示编辑界面
            handleEdit: function (row, type) {

                // this.getlist(type);
                this.editFormVisible = true;

                this.editForm = {
                    id: row.id,
                    alarmFlow: ''
                }
            },
            //显示新增界面
            handleAdd: function () {
                this.addFormVisible = true;
                this.addForm = {
                    name: '',
                    remark: ''
                };
            },
            //编辑
            editSubmit: function () {
                this.$refs.editForm.validate((valid) => {
                    if (valid) {
                        this.$confirm('确认提交吗？', '提示', {}).then(() => {
                            //NProgress.start();
                            let para = Object.assign({}, this.editForm);
                            if (this.editForm.alarmFlow > 100 || this.editForm.alarmFlow < 0) {
                                this.$message({
                                    message: '流量阈值范围0-100',
                                    type: 'warning'
                                });
                                return false;
                            }
                            device_flow_put(para).then((res) => {
                                this.begCode(res.code, res.message);

                                this.editLoading = false;
                                if (res.code == 0) {
                                    //NProgress.done();
                                    this.$message({
                                        message: '修改成功',
                                        type: 'success'
                                    });
                                    this.$refs['editForm'].resetFields();
                                    this.editFormVisible = false;
                                    this.getUsers();
                                }
                            });
                        });
                    }
                });
            },
            //新增
            addSubmit: function () {
                this.$refs.addForm.validate((valid) => {
                    if (valid) {
                        this.$confirm('确认提交吗？', '提示', {}).then(() => {
                            this.addLoading = true;
                            //NProgress.start();
                            let para = Object.assign({}, this.addForm);

                            device_model_post(para).then((res) => {
                                this.begCode(res.code, res.message);
                                this.addLoading = false;
                                //NProgress.done();
                                this.$message({
                                    message: '提交成功',
                                    type: 'success'
                                });
                                this.$refs['addForm'].resetFields();
                                this.addFormVisible = false;
                                this.getUsers();
                            });
                        });
                    }
                });
            },
            selsChange: function (sels) {
                this.sels = sels;
            },
            getlist(type) {
                let para = {
                    pageNo: 1,
                    pageSize: 9999,
                    type: type
                }

                device_upgrade_query(para).then((res) => {
                    this.begCode(res.code, res.message);
                    this.listLoading = false;
                    this.bag = res.data.list;
                });
                device_argument_query(para).then((res) => {
                    this.begCode(res.code, res.message);
                    this.listLoading = false;
                    this.parameter = res.data.list;
                });
            },
            //批量删除
            batchRemove: function (type) {
                var ids = this.sels.map(item => item.deviceId).toString();
                this.getlist(type)
                this.editFormVisible = true;
                this.editForm = {
                    type: type,
                    idList: ids.split(','),
                    ftpUser: '',
                    deviceUpgradeId: '',
                    deviceArgumentId: '',
                    ftpPassword: ''
                }
                //NProgress.start();

                // device_model_delete(para).then((res) => {
                //      this.begCode(res.code,res.message);
                //     this.listLoading = false;
                //     //NProgress.done();
                //     this.$message({
                //         message: '删除成功',
                //         type: 'success'
                //     });
                //     this.getUsers();
                // });

            }
        },
        mounted() {
            this.usertype = JSON.parse(sessionStorage.getItem('user')).type;
            if (this.$route.query.name) {
                this.filters.name = this.$route.query.name;
            }
            this.menubt = localStorage.getItem('menubt');
            let parauser = {
                pageNo: 1,
                pageSize: 9999,
                type: 1
            }
            let para1 = {
                pageNo: 1,
                pageSize: 9999,
                type: 0
            }
            user_query(para1).then((res) => {

                this.begCode(res.code, res.message);
                this.userclist = res.data.list;
                // if (this.userclist[0]) {

                //     this.scade = this.userclist[0].userId;
                // }
                this.scade = this.userID
                // this.select_scade();

            });
            user_querycompany(parauser).then((res) => {

                this.begCode(res.code, res.message);
                this.firmlist = res.data.list;

                console.log(this.firmlist)
            });

            this.getUsers();
            this.deviceList();


        }
    }
</script>

<style scoped>

</style>